package com.qfedu.agro.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Jwt工具类
 * @author 千锋健哥
 */
public class JwtUtil {

    //有效期为
    public static final Long JWT_TTL = 21600000L;// 60 * 60 *1000 *6  六个小时
    @Value("${jwt.secret}")
    private String jwtSecret = "8G>6$pZ7#qY%&A2";
    /**
     * 创建token
     * @param id
     * @param subject
     * @param ttlMillis
     * @return
     */
    public String createJWT(String id, String subject, Long ttlMillis) {

        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if(ttlMillis==null){
            ttlMillis=JwtUtil.JWT_TTL;
        }
        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);

        Map<String, Object> map = new HashMap<>();
        map.put("id", id);

        JwtBuilder builder = Jwts.builder()
                .setId(id)
                .setClaims(map)              //唯一的ID
                .setSubject(subject)   // 主题  可以是JSON数据
                .setIssuer("admin")     // 签发者
                .setIssuedAt(now)      // 签发时间
                .signWith(signatureAlgorithm, jwtSecret) //使用HS256对称加密算法签名, 第二个参数为秘钥
                .setExpiration(expDate);// 设置过期时间
        return builder.compact();
    }

    /**
     * 解析
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public Claims parseJWT(String jwt) {

        return Jwts.parser()
                .setSigningKey(jwtSecret)
                .parseClaimsJws(jwt)
                .getBody();
    }


//    public static void main(String[] args) {
//        Claims claims = new JwtUtil().parseJWT("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxIiwic3ViIjoie1wiYmlydGhkYXlcIjo5MTUxMjAwMDAwMDAsXCJjb21wYW55SWRcIjoxLFwiY29tcGFueU5hbWVcIjpcIuWNg-mUi-S6kuiBlFwiLFwiY3JlYXRlVGltZVwiOjE2Nzc2MzI1MzIwMDAsXCJlbWFpbFwiOlwiYWRtaW5AbWFuYWdlci5jb21cIixcImdlbmRlclwiOlwibWFsZVwiLFwiZ3JvdXBJZFwiOjEsXCJpZFwiOjEsXCJqb2luRGF0ZVwiOjE2NzY0NzY4MDAwMDAsXCJvcmRlck5vXCI6MSxcInBhc3N3b3JkXCI6XCIwMTkyMDIzYTdiYmQ3MzI1MDUxNmYwNjlkZjE4YjUwMFwiLFwicmVtYXJrXCI6XCIxMTFcIixcInNhbGFyeVwiOjE1MDAwLFwic3RhdGVcIjoxLFwic3RhdGlvblwiOlwiYWRtaW4xMjNcIixcInRlbGVwaG9uZVwiOlwiMTM5ODc2NTQzMjFcIixcInVwZGF0ZVRpbWVcIjoxNjc3NjMyNTMyMDAwLFwidXNlcm5hbWVcIjpcImFkbWluXCJ9IiwiaXNzIjoiYWRtaW4iLCJpYXQiOjE2ODUzNzE3MjYsImV4cCI6MTY4NTk3NjUyNn0.T9_6bvlb4yT4WfzP6cdzgQ91m_gpvzeUb2oc0Qpmhx0");
//
//        System.out.println(claims.get("id"));
//
//    }

}
